package priv.zgh.forum.check.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import priv.zgh.forum.check.service.MsmService;
import priv.zgh.forum.utils.R;
import priv.zgh.forum.utils.RandomUtil;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@CrossOrigin
@RequestMapping("/msm")
public class MsmController {
    private MsmService msmService;
    @Autowired
    public void setMsmService(MsmService msmService) {
        this.msmService = msmService;
    }
    private RedisTemplate<String,String> redisTemplate;
    @Autowired
    public void setRedisTemplate(RedisTemplate<String, String> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    // 发送短信的方法
    @GetMapping("/send/{phone}")
    public R sendMsm(@PathVariable String phone){
        // 从redis获取验证码,如果获取就直接返回
        String code = redisTemplate.opsForValue().get(phone);
        if(!StringUtils.isEmpty(code)){
            return R.ok();
        }
        // 获取不到就用腾讯云发送
        // 生成随机值,使用腾讯云发送
        code = RandomUtil.getFourBitRandom();
        Map<String,Object> param = new HashMap<>();
        param.put("code",code);
        boolean isSend = msmService.send(param,phone);
        if(isSend) {
            redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES); // 设置redis数据的生存时间未5分钟
            return R.ok();
        }else{
            return R.error().message("发送短信失败!");
        }
    }
}
